package com.sky.utils;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownLoad {
    public Boolean DownLoadImg(String link, String path) throws IOException {
        URL url = new URL(link);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("GET");

        connection.setConnectTimeout(10*1000);

        InputStream is = connection.getInputStream();

        System.out.println("inputStream:"+is.toString());

        byte[] data = readInputStream(is);

        File imageFile = new File(path);

        if (!imageFile.exists()){
            imageFile.mkdirs();
        }

        FileOutputStream outputStream = new FileOutputStream(imageFile);

        outputStream.write(data);

        outputStream.close();

        return true;
    }

    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[6024];
        Integer len ;
        while ((len = inputStream.read(buffer)) != -1){
            outStream.write(buffer,0,len);
//            System.out.println("len:"+len);
        }

        inputStream.close();
        return outStream.toByteArray();
    }
}
